import React from 'react';
import Picker from 'rmc-picker';
import { CSSTransitionGroup } from 'react-transition-group';
import cx from 'classnames';
import s from './index.m.less';

const addZero = num => {
    if (typeof num === 'string') return num;
    if (num !== 0 && !num) return num;

    return num < 10 ? `0${num}` : num;
};

export default class Frm2Inner extends React.Component {
    static defaultProps = {
        title: '',
        onChange: () => {},
        onCancel: () => {},
        cancelName: '取消',
        confirmName: '确定',
        unit: 'unit', // 单位
        value: [], // 值，数字数组
        beginNumber: undefined, // 开始，数字，
        endNumber: undefined, // 结束
        middle: '至', // 中间的字
    };

    constructor(p) {
        super(p);
        this.state = {
            value: [],
        };
        this.reset(this.props);
    }

    componentWillReceiveProps(np) {
        np.uuid !== this.props.uuid && this.reset(np, 1);
    }

    reset = (props, isUpdata) => {
        const {
            type, unit, value, beginNumber, endNumber
        } = props;
        this.DataBase.init(type, unit, beginNumber, endNumber);
        const [v1, v2] = value;
        if (isUpdata) {
            this.setState({
                value: [addZero(v1), addZero(v2)],
            });
        } else {
            this.state.value = [addZero(v1), addZero(v2)];
        }
    };

    // 序列数据库
    DataBase = {
        year: {
            text: '年',
            start: new Date().getFullYear(),
            end: new Date().getFullYear() + 5,
        },
        month: {
            text: '月',
            start: 1,
            end: 12,
        },
        day: {
            text: '日',
            start: 1,
            end: 31,
        },
        hour: {
            text: '时',
            start: 0,
            end: 24,
        },
        min: {
            text: '分',
            start: 0,
            end: 59,
        },
        second: {
            text: '秒',
            start: 0,
            end: 59,
        },
        user: null,
        current: 'day',
        get data() {
            return this[this.current];
        },
        init(type, unit, limitStart, limitEnd) {
            if (!type) {
                throw new Error('参数错错误:type为必填属性');
            }

            if (limitStart > limitEnd) {
                throw new Error('参数错错误:start>end');
            }

            const data = this[type];
            // debugger
            if (!data) {
                if (limitStart === undefined || limitEnd === undefined || !unit) {
                    throw new Error('参数错错误:自定义参数不全');
                }
                this.user = {
                    text: unit,
                    start: limitStart,
                    end: limitEnd,
                };
                this.current = 'user';
                return true;
            }
            const { start, end } = data;

            unit && (data.text = unit);

            if (limitStart) {
                if (limitStart >= end) {
                    throw new Error(`参数错错误:start应小于${end}`);
                }
                data.start = limitStart;
            }

            if (limitEnd) {
                if (limitEnd <= start) {
                    throw new Error(`参数错错误:end应大于${start}`);
                }
                data.end = limitEnd;
            }

            this.current = type;
            return true;
        },
    };

    // 处理单列日期选择
    handleChange = valueIdx => value => {
        const [v1, v2] = this.state.value;
        const ret = [v1, v2];
        ret[valueIdx] = value;
        this.setState({ value: ret });

        const [p1, p2] = ret;

        valueIdx === 0
            ? +value <= +v2 && this.props.onChange([+p1, +p2])
            : +value >= +v1 && this.props.onChange([+p1, +p2]);
    };

    submit = () => {
        this.props.onOk();
        this.props.close();
    };

    cancel = () => this.props.onCancel();

    render() {
        const {
            title, middle, cancelName, confirmName
        } = this.props;
        const { value } = this.state;
        const { data } = this.DataBase;
        const { start, end, text } = data;
        const colums = [text, middle, text];

        return (
            <div
                data-name="__fixed_key_for_picker_modal__"
                className={s.layer}
                onClick={e => {
                    e.preventDefault();
                    e.stopPropagation();
                }}
            >
                <div className={s.header}>
                    <div className={cx(s.cancel, 'modal-close')} onClick={this.cancel}>
                        {cancelName}
                    </div>
                    <CSSTransitionGroup
                        className={s.titleTrans}
                        transitionName={{
                            enter: s.enter,
                            enterActive: s.enterActive,
                            leave: s.leave,
                            leaveActive: s.leaveActive,
                        }}
                        transitionEnter
                        transitionLeave
                        transitionEnterTimeout={400}
                        transitionLeaveTimeout={400}
                        component="div"
                    >
                        <div className={s.title} key={title}>
                            {title}
                        </div>
                    </CSSTransitionGroup>

                    <div className={s.confirm} onClick={this.submit}>
                        {confirmName}
                    </div>
                </div>

                <div className={s.pk}>
                    {colums.map((ut, i) => {
                        let [vSt, vEd] = value;
                        if (!vSt && vSt !== 0) {
                            vSt = start;
                        }
                        // 无值,设置默认值
                        if (!vEd && vEd !== 0) {
                            vEd = end / 2 > vSt ? Math.ceil(end / 2) : vSt + 1;
                        }

                        // 中间那个 ‘至'
                        if (i === 1) {
                            return (
                                <div className={cx(s.colum, s.middle)} key={ut}>
                                    <Picker disabled type="stanley" selectedValue="a">
                                        <Picker.Item value="a">{ut}</Picker.Item>
                                        <Picker.Item value="a">
                                            <div className={cx(s.error, vSt > vEd && s.show)}>选择有误!</div>
                                        </Picker.Item>
                                    </Picker>
                                </div>
                            );
                        }

                        const styleNormal = { width: '80%' };
                        const styleDisable = { width: '80%', color: '#bbb' };

                        const valueIdx = i === 0 ? 0 : 1;
                        let pValue = vSt;
                        const cells = [];

                        // 开始数据段
                        if (valueIdx === 0) {
                            for (let val = start; val <= end; val++) {
                                cells.push({ val: addZero(val), style: val <= vEd ? styleNormal : styleDisable });
                            }
                        }

                        // 结束数据段
                        if (valueIdx === 1) {
                            pValue = vEd;
                            for (let val = start; val <= end; val++) {
                                cells.push({ val: addZero(val), style: val >= vSt ? styleNormal : styleDisable });
                            }
                        }

                        const items = cells.map(({ val, style }) => (
                            <Picker.Item value={val} key={val}>
                                <div style={style}>{val}</div>
                            </Picker.Item>
                        ));

                        return (
                            <div className={s.colum} key={i}>
                                <div className={cx(s.unit, { [s.year]: ut === '年' })}>{ut}</div>
                                <Picker
                                    type="stanley"
                                    selectedValue={pValue}
                                    onValueChange={this.handleChange(valueIdx)}
                                    defaultSelectedValue={pValue}
                                >
                                    {items}
                                </Picker>
                            </div>
                        );
                    })}
                </div>
            </div>
        );
    }
}
